/*
 * @Description:
 * @Author: Junhuang
 * @Date: 2022-04-01 15:08:08
 * @LastEditTime: 2022-05-10 15:20:20
 * @LastEditors: Junhuang
 * @Reference:
 */
'use strict';
// 引入
const crypto = require('crypto');
module.exports = app => {
  const { INTEGER, STRING, DATE, TEXT } = app.Sequelize;
  // 配置（重要：一定要配置详细，一定要！！！）
  const Admin = app.model.define('sys_admin', {
    id: { type: INTEGER(20), primaryKey: true, allowNull: false, autoIncrement: true, comment: '主键id' },
    no: { type: STRING(10), allowNull: false, defaultValue: '', comment: '工号', unique: true },
    department_id: { type: INTEGER(20), allowNull: false, comment: '部门id' },
    username: { type: STRING(20), allowNull: false, defaultValue: '', comment: '用户名称', unique: true },
    name: { type: STRING(50), allowNull: false, defaultValue: '', comment: '昵称' },
    password: {
      type: STRING, allowNull: false, defaultValue: '', comment: '密码',
      set(val) {
        const hmac = crypto.createHash('sha256', app.config.crypto.secret);
        hmac.update(val);
        this.setDataValue('password', hmac.digest('hex'));
      },
    },
    avatar: { type: STRING(255), defaultValue: '', comment: '图像地址' },
    roles: { type: STRING(255), defaultValue: '', comment: '角色' },
    introduction: { type: TEXT, defaultValue: '', comment: '说明' },
    status: { type: INTEGER(2), allowNull: false, defaultValue: 0, comment: '状态' },
    created_time: {
      type: DATE,
      // 获取器，对获取的数据库中的字段进行处理，此处将数据库中的时间字段转换为timestamp
      get() {
        const val = this.getDataValue('created_time');
        return (new Date(val)).getTime();
      },
    },
    updated_time: {
      type: DATE,
      // 获取器，对获取的数据库中的字段进行处理，此处将数据库中的时间字段转换为timestamp
      get() {
        const val = this.getDataValue('updated_time');
        return (new Date(val)).getTime();
      },
    },
  }, {
    timestamps: true, // 是否自动写入时间戳
    tableName: 'sys_admin', // 自定义数据表名称
  });

  // 关联关系
  Admin.associate = function() {
    // 关联部门
    Admin.belongsTo(app.model.Department, {
      foreignKey: 'department_id',
      as: 'department',
    });

    Admin.belongsToMany(app.model.Role, {
      through: app.model.RoleAdmin,
      foreignKey: 'admin_id',
      as: 'myroles',
    });
  };

  return Admin;
};
